<template>
  <div style="width: 100%;">
    <el-container style="height: 100vh;">
      <!-- 侧边栏 -->
      <el-aside width="220px" style="background: #001529;">
        <div class="logo">{{ sysSettingsForm.name }}</div>
        <el-menu :default-active="activeMenu" background-color="#001529" text-color="#fff" active-text-color="#409EFF"
          @select="handleMenuSelect">
          <el-menu-item index="dashboard">
            <el-icon><i-ep-menu /></el-icon>
            <span>仪表盘</span>
          </el-menu-item>
          <el-sub-menu index="user-manage">
            <template #title>
              <el-icon><i-ep-user /></el-icon>
              <span>用户管理</span>
            </template>
            <el-menu-item index="user">
              <el-icon><i-ep-user /></el-icon>
              <span>成员管理</span>
            </el-menu-item>
            <el-menu-item index="role">
              <el-icon><i-ep-s-check /></el-icon>
              <span>角色管理</span>
            </el-menu-item>
            <el-menu-item index="permission">
              <el-icon><i-ep-lock /></el-icon>
              <span>权限管理</span>
            </el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="content-manage">
            <template #title>
              <el-icon><i-ep-document /></el-icon>
              <span>内容管理</span>
            </template>
            <el-menu-item index="articles">
              <el-icon><i-ep-document /></el-icon>
              <span>文章管理</span>
            </el-menu-item>
            <el-menu-item index="files">
              <el-icon><i-ep-folder /></el-icon>
              <span>文件管理</span>
            </el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="sys-manage">
            <template #title>
              <el-icon><i-ep-setting /></el-icon>
              <span>系统管理</span>
            </template>
            <el-menu-item index="menus">
              <el-icon><i-ep-menu /></el-icon>
              <span>菜单管理</span>
            </el-menu-item>
            <el-menu-item index="sys-settings">
              <el-icon><i-ep-setting /></el-icon>
              <span>系统设置</span>
            </el-menu-item>
            <el-menu-item index="sys-log">
              <el-icon><i-ep-warning /></el-icon>
              <span>日志管理</span>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>
      
      <!-- 主体 -->
      <el-container>
        <!-- 顶部栏 -->
        <el-header class="header-bar">
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="breadcrumb-nav">
            <el-breadcrumb-item v-for="(item, idx) in navHistory" :key="idx" @click="navigateTo(item, idx)">
              <el-icon v-if="idx === 0"><i-ep-menu /></el-icon>
              <span>{{ item.title }}</span>
            </el-breadcrumb-item>
          </el-breadcrumb>
          
          <div class="header-right">
            <el-dropdown>
              <span class="el-dropdown-link">
                你好，{{ loginUsername }}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goProfileCenter">个人中心</el-dropdown-item>
                  <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        
        <!-- 内容区 -->
        <el-main class="main-full">
          <div class="content-page">
            <!-- 动态组件切换 -->
            <component :is="currentComponent" />
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { getApiUrl } from '../config/api.js'

// 导入组件
import Dashboard from './Dashboard.vue'
import UserManagement from './UserManagement.vue'
import RoleManagement from './RoleManagement.vue'
import PermissionManagement from './PermissionManagement.vue'
import ArticleManagement from './ArticleManagement.vue'
import FileManagement from './FileManagement.vue'
import MenuManagement from './MenuManagement.vue'
import SystemSettings from './SystemSettings.vue'
import LogManagement from './LogManagement.vue'
import UserProfile from './UserProfile.vue'

// 获取登录用户名
const loginUsername = ref(localStorage.getItem('loginUsername') || '管理员')
const router = useRouter()

// 刷新记忆当前菜单
const ACTIVE_MENU_KEY = 'activeMenuKey'
const activeMenu = ref(localStorage.getItem(ACTIVE_MENU_KEY) || 'dashboard')

// 系统设置数据
const sysSettingsForm = reactive({
  name: '通用后台管理系统',
  version: '1.0.0',
  language: 'zh-CN',
  timezone: 'Asia/Shanghai',
  adminEmail: 'admin@test.com'
})

// 面包屑导航
const navHistory = ref([
  { title: '仪表盘', path: '/dashboard', menuKey: 'dashboard' }
])

const menuTitles = {
  dashboard: '仪表盘',
  'user-manage': '用户管理',
  user: '成员管理',
  role: '角色管理',
  permission: '权限管理',
  menu: '菜单管理',
  'sys-manage': '系统管理',
  'sys-settings': '系统设置',
  'sys-log': '日志管理',
  profile: '个人中心'
}

// 动态组件映射
const componentMap = {
  dashboard: Dashboard,
  user: UserManagement,
  role: RoleManagement,
  permission: PermissionManagement,
  articles: ArticleManagement,
  files: FileManagement,
  menus: MenuManagement,
  'sys-settings': SystemSettings,
  'sys-log': LogManagement,
  profile: UserProfile
}

// 当前组件
const currentComponent = computed(() => {
  return componentMap[activeMenu.value] || Dashboard
})

const handleMenuSelect = (menuKey) => {
  activeMenu.value = menuKey
  localStorage.setItem(ACTIVE_MENU_KEY, menuKey)
  
  // 如果点击的是当前路径的最后一项，不做处理
  if (navHistory.value[navHistory.value.length - 1].menuKey === menuKey) return
  
  // 如果点击的是已存在的路径项，回退到该层级
  const existingIndex = navHistory.value.findIndex(item => item.menuKey === menuKey)
  if (existingIndex >= 0) {
    navHistory.value = navHistory.value.slice(0, existingIndex + 1)
  } else {
    navHistory.value.push({
      title: menuTitles[menuKey],
      path: `/${menuKey}`,
      menuKey
    })
  }
}

// 处理面包屑点击
const navigateTo = (item, idx) => {
  // 点击当前页面不做处理
  if (idx === navHistory.value.length - 1) return
  
  // 截断到点击的层级
  navHistory.value = navHistory.value.slice(0, idx + 1)
  activeMenu.value = item.menuKey
  localStorage.setItem(ACTIVE_MENU_KEY, item.menuKey)
}

// 个人中心切换
function goProfileCenter() {
  activeMenu.value = 'profile'
  localStorage.setItem(ACTIVE_MENU_KEY, 'profile')
  
  // 面包屑处理
  if (navHistory.value[navHistory.value.length - 1].menuKey !== 'profile') {
    navHistory.value.push({
      title: menuTitles['profile'],
      path: '/profile',
      menuKey: 'profile'
    })
  }
}

// 登出
const handleLogout = async () => {
  try {
    const token = localStorage.getItem('token')
    if (token) {
      await axios.post(getApiUrl('/auth/logout'), {}, {
        headers: { 'Authorization': `Bearer ${token}` }
      })
    }
  } catch (error) {
    console.error('登出请求失败:', error)
  } finally {
    // 无论请求是否成功，都清除本地存储并跳转
    localStorage.removeItem('token')
    localStorage.removeItem('loginUsername')
    router.push('/')
  }
}
</script>

<style scoped>
.logo {
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  height: 56px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
}

.header-bar {
  background: #fff;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 56px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
}

.header-right {
  margin-right: 32px;
}

.main-full {
  width: 100%;
  padding: 0;
  background: #f5f6fa;
  display: flex;
  justify-content: center;
  overflow-y: auto;
  scrollbar-width: none;
}

.main-full::-webkit-scrollbar {
  display: none;
}

.content-page {
  background: #fff;
  padding: 24px 0 24px 0;
  border-radius: 8px;
  min-height: 600px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  width: 98vw;
  max-width: 1920px;
  height: auto;
  box-sizing: border-box;
  margin: 24px auto 0 auto;
}

.breadcrumb-nav {
  flex: 1;
  margin-left: 24px;
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  display: flex;
  align-items: center;
}

.header-bar {
  display: flex;
  align-items: center;
}

/* 隐藏 el-main 的滚动条但允许滚动 */
::v-deep .el-main {
  overflow-y: auto !important;
  scrollbar-width: none;
}
::v-deep .el-main::-webkit-scrollbar {
  display: none;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .content-page {
    width: 95vw;
    margin: 20px auto 0 auto;
    padding: 20px 0 20px 0;
  }
  
  .logo {
    font-size: 18px;
    padding: 28px 0 20px 0;
  }
}

@media (max-width: 768px) {
  .content-page {
    width: 92vw;
    margin: 15px auto 0 auto;
    padding: 15px 0 15px 0;
    min-height: 500px;
  }
  
  .logo {
    font-size: 16px;
    padding: 24px 0 16px 0;
  }
  
  .header-right {
    margin-right: 20px;
  }
  
  .breadcrumb-nav {
    margin-left: 15px;
  }
}

@media (max-width: 480px) {
  .content-page {
    width: 90vw;
    margin: 10px auto 0 auto;
    padding: 10px 0 10px 0;
    min-height: 400px;
  }
  
  .logo {
    font-size: 14px;
    padding: 20px 0 12px 0;
  }
  
  .header-right {
    margin-right: 15px;
  }
  
  .breadcrumb-nav {
    margin-left: 10px;
  }
}

/* 当F12开发者工具打开时的特殊处理 */
@media (max-height: 600px) {
  .content-page {
    min-height: auto;
    margin: 10px auto 0 auto;
    padding: 10px 0 10px 0;
  }
  
  .logo {
    padding: 16px 0 8px 0;
  }
}

/* 确保在小屏幕上表单元素也能正常显示 */
@media (max-width: 400px) {
  .content-page {
    width: 88vw;
    margin: 8px auto 0 auto;
    padding: 8px 0 8px 0;
  }
  
  .logo {
    font-size: 12px;
    padding: 16px 0 8px 0;
  }
}
</style> 